package listeners;

import gui.MainFrame;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.swing.DefaultListModel;

import model.User;

public class UpdateUserListener implements MessageListener {

	private DefaultListModel<User> userListModel;
	private Connection connection;
	private Session session;
	private MessageConsumer consumer;
	
	public UpdateUserListener(DefaultListModel<User> userListModel) {
		this.userListModel=userListModel;
		
		try {
			final Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jboss.naming.remote.client.InitialContextFactory");
			env.put(Context.PROVIDER_URL, "remote://"+MainFrame.getInstance().getLocalAddress()+":4447");
			env.put(Context.SECURITY_PRINCIPAL, "guest");
			env.put(Context.SECURITY_CREDENTIALS, "guestguest");
			Context context = new InitialContext(env);
			ConnectionFactory cf = (ConnectionFactory) context
					.lookup("jms/RemoteConnectionFactory");
			final Topic topic = (Topic) context
					.lookup("jms/topic/mojTopic2");
			context.close();
			connection = cf.createConnection("guest", "guestguest");
			session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);

			connection.start();

			consumer = session.createConsumer(topic);
			consumer.setMessageListener(this);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void disconnect() {
		try {
			connection.close();
			session.close();
			consumer.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onMessage(Message message) {
		if(message instanceof ObjectMessage) {
			ObjectMessage objMsg = (ObjectMessage) message;
			User user;
			try {
				user = (User) objMsg.getObject();
				if(userListModel.contains(user)) {
					userListModel.removeElement(user);
				}
				else
					userListModel.addElement(user);
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
